package com.example.hcd.tool;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;

public class ImageBtnMove extends ImageView{
	private Activity mActivity;
	private int startX;  
	private int startY;
	private SharedPreferences	sp;
	private long firClick = -1;
	private long secClick;
	private OnDoubleClickListener listen = null;
	public ImageBtnMove(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}
	public void setListen(OnDoubleClickListener listen)
	{
		this.listen = listen;
	}
	
	public void setActivity(Activity mActivitys)
	{
		this.mActivity = mActivitys;
		
		this.sp = mActivity.getSharedPreferences( "config" , Context.MODE_PRIVATE );

		final float screenHeight = mActivity.getWindowManager().getDefaultDisplay()
				.getHeight();
		@SuppressWarnings("deprecation")
		final float screenWidth = mActivity.getWindowManager().getDefaultDisplay()
				.getWidth();
		setOnTouchListener( new OnTouchListener() {
			
			@Override
			public boolean onTouch( View v, MotionEvent event ) {
				switch ( event.getAction() ) {
				case MotionEvent.ACTION_DOWN:
					startX = ( int ) event.getRawX();
					startY = ( int ) event.getRawY();
					
					if (event.getAction() == MotionEvent.ACTION_DOWN) 
					   {
							
				           secClick = System.currentTimeMillis();
				           if (secClick - firClick < 1000) {
				        	   //添加雙擊時間
				        	   if(listen!=null)
				        	   {
				        		   firClick = -1;
				        		   listen.OnDoubleClick(getRootView());
				        	   }
				           }else
				           {
				           	firClick = secClick;
				           }
					
					   	}
					
					break;
				case MotionEvent.ACTION_MOVE:
					int newX = ( int ) event.getRawX();
					int newY = ( int ) event.getRawY();

					int dx = newX - startX;
					int dy = newY - startY;

					
					int l = getLeft();
					int r = getRight();
					int t = getTop();
					int b = getBottom();

					int newt = t + dy;
					int newb = b + dy;
					int newl = l + dx;
					int newr = r + dx;

					if ( ( newl < 0 ) || ( newt < 0 )
							|| ( newr > screenWidth )
							|| ( newb > screenHeight ) ) {
						break;
					}

					
					layout( newl , newt , newr , newb );
					startX = ( int ) event.getRawX();
					startY = ( int ) event.getRawY();

					break;
				case MotionEvent.ACTION_UP:
					int lastx = getLeft();
					int lasty = getTop();
					Editor editor = sp.edit();
					editor.putInt( "lastx" , lastx );
					editor.putInt( "lasty" , lasty );
					editor.commit();
					break;
				}
				return true;
			}
		} );
	}

}
